package com.chain.BrotherExchange.ui.fragment;

import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.RadioGroup;

import com.chain.BrotherExchange.C;
import com.chain.BrotherExchange.R;
import com.chain.BrotherExchange.data.Resource;
import com.chain.BrotherExchange.data.model.QuotationTypes;
import com.chain.BrotherExchange.data.model.UserPayment;
import com.chain.BrotherExchange.event.LoginEvent;
import com.chain.BrotherExchange.event.LogoutEvent;
import com.chain.BrotherExchange.event.SubmitAlipayEvent;
import com.chain.BrotherExchange.event.SubmitBankCardEvent;
import com.chain.BrotherExchange.event.SubmitPayPalEvent;
import com.chain.BrotherExchange.event.SubmitRealNameAuthenticationEvent;
import com.chain.BrotherExchange.event.SubmitWeChatPayEvent;
import com.chain.BrotherExchange.ui.activity.PaymentActivity;
import com.chain.BrotherExchange.ui.activity.PersonalCenterActivity;
import com.chain.BrotherExchange.ui.activity.PublishTransactionOrderActivity;
import com.chain.BrotherExchange.ui.activity.SettingTransactionPasswordActivity;
import com.chain.BrotherExchange.ui.adapter.SimpleFragmentPagerAdapter;
import com.chain.BrotherExchange.ui.core.AbsNetworkStateFragment;
import com.chain.BrotherExchange.ui.listener.LoginInterceptListener;
import com.chain.BrotherExchange.utils.ActivityBarHelper;
import com.chain.BrotherExchange.utils.Androids;
import com.chain.BrotherExchange.viewmodel.IDAuthenticationViewModel;
import com.chain.BrotherExchange.viewmodel.PaymentViewModel;
import com.chain.BrotherExchange.viewmodel.QuotationViewModel;
import com.chain.BrotherExchange.viewmodel.core.ViewModelProviders;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;

/**
 * 法币
 */
public class LegalTenderFragment extends AbsNetworkStateFragment {

    public static Fragment newInstance() {
        return new LegalTenderFragment();
    }

    @Bind(R.id.action_image) View mActionImage;
    @Bind(R.id.purchase_view_pager) ViewPager mPurchaseViewPager;
    @Bind(R.id.sell_view_pager) ViewPager mSellViewPager;
    @Bind(R.id.legal_tender_group) RadioGroup mLegalTenderGroup;

    private boolean setPaymentMethod;
    private PaymentViewModel mPaymentViewModel;
    int authenticationState = C.API_UNAUTHORIZED;
    private QuotationViewModel mQuotationViewModel;
    private UserPayment.DataBean.SetpaysBean mSetpays;
    private IDAuthenticationViewModel mIdAuthenticationViewModel;

    @Override
    protected int getLayoutID() {
        return R.layout.fragment_legal_tender;
    }

    @Override
    protected boolean useEventBus() {
        return true;
    }

    @Override
    protected void onVisible() {
        ActivityBarHelper.setTransparentDarkColorStatus(getActivity());
        initAuthentication();
    }

    @Override
    protected void initActions() {
        mQuotationViewModel = ViewModelProviders.of(this).get(QuotationViewModel.class);
        mPaymentViewModel = ViewModelProviders.of(this).get(PaymentViewModel.class);
        mIdAuthenticationViewModel = ViewModelProviders.of(this).get(IDAuthenticationViewModel.class);

        // 发布订单
        mActionImage.setOnClickListener(new LoginInterceptListener(v -> publishTransactionOrder()));

        // 切换购买/出售
        mLegalTenderGroup.setOnCheckedChangeListener((group, checkedId) -> {
            switch (checkedId) {
                case R.id.purchase_button:
                    mPurchaseViewPager.setVisibility(View.VISIBLE);
                    mSellViewPager.setVisibility(View.GONE);
                    break;
                case R.id.sell_button:
                    mPurchaseViewPager.setVisibility(View.GONE);
                    mSellViewPager.setVisibility(View.VISIBLE);
                    break;
            }
        });

        mLegalTenderGroup.check(R.id.purchase_button);
        initLegalTenderTitles();
    }

    // 发布订单
    private void publishTransactionOrder() {
        if (!Androids.LocalConfig.isSetTransactionPassword()) {
            new AlertDialog.Builder(getContext()).setTitle(R.string.improve_information)
                    .setMessage(R.string.dialog_fund_password)
                    .setPositiveButton(R.string.go_setting, (dialog, which) ->
                            SettingTransactionPasswordActivity.launch(getContext())
                    ).setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss()).show();
        } else if (setPaymentMethod) {
            new AlertDialog.Builder(getContext()).setTitle(R.string.improve_information)
                    .setMessage(R.string.dialog_payment)
                    .setPositiveButton(R.string.go_setting, (dialog, which) ->
                            PaymentActivity.launch(getContext())
                    ).setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss()).show();
        } else if (authenticationState == C.API_UNAUTHORIZED || authenticationState == C.API_AUTHENTICATION_FAILURE) {
            new AlertDialog.Builder(getContext()).setTitle(R.string.improve_information)
                    .setMessage(R.string.dialog_secondary_certification)
                    .setPositiveButton(R.string.go_setting, (dialog, which) ->
                            PersonalCenterActivity.launch(getContext())
                    ).setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss()).show();
        } else if (authenticationState == C.API_IN_AUTHENTICATION) {
            Androids.makeText(R.string.message_secondary_certification_ing);
        } else {
            PublishTransactionOrderActivity.launch(getContext(), mSetpays);
        }
    }

    private void initLegalTenderTitles() {
        mQuotationViewModel.quotationTypes().observe(this, resource ->
                Resource.load(getContext(), resource, this, result -> {
                    List<Fragment> purchaseFragmentList = new ArrayList<>();
                    List<Fragment> sellFragmentList = new ArrayList<>();
                    List<String> titleList = new ArrayList<>();
                    for (QuotationTypes.DataBean.ListBean listBean : result) {
                        int tokenId = listBean.getToken_id();
                        titleList.add(listBean.getMark());
                        purchaseFragmentList.add(LegalTenderDealListFragment.newInstance(C.API_PURCHASE, tokenId));
                        sellFragmentList.add(LegalTenderDealListFragment.newInstance(C.API_SELL, tokenId));
                    }

                    // 购买
                    mPurchaseViewPager.setAdapter(new SimpleFragmentPagerAdapter(
                            getFragmentManager(), purchaseFragmentList, titleList));

                    // 出售
                    mSellViewPager.setAdapter(new SimpleFragmentPagerAdapter(
                            getFragmentManager(), sellFragmentList, titleList));
                })
        );

        // 用户支付方式
        mPaymentViewModel.userPayment().observe(this, resource -> {
            if (resource.state == Resource.Status.SUCCESS) {
                mSetpays = resource.source.getSetpays();
                setPaymentMethod = mSetpays.isSetPayment();
            }
        });
    }

    private void initAuthentication(){
        mIdAuthenticationViewModel.isAuthentication().observe(this, resource -> {
            if (resource.state == Resource.Status.SUCCESS) {
                authenticationState = resource.source.getCheck_mark_second();
            }
        });
    }

    @Override
    public void onAnewRequest() {
        initLegalTenderTitles();
    }

    @Subscribe
    public void loginEvent(LoginEvent loginEvent) {
        // 用户支付方式
        mPaymentViewModel.userPayment().observe(this, resource -> {
            if (resource.state == Resource.Status.SUCCESS) {
                mSetpays = resource.source.getSetpays();
                setPaymentMethod = mSetpays.isSetPayment();
            }
        });

        // 实名认证
        initAuthentication();
    }

    @Subscribe
    public void logoutEvent(LogoutEvent event) {
        mSetpays = null;
        setPaymentMethod = false;
        authenticationState = C.API_UNAUTHORIZED;
    }

    @Subscribe
    public void addBankCardEvent(SubmitBankCardEvent event) {
        if (mSetpays != null) {
            mSetpays.setBank_pay(1);
            setPaymentMethod = false;
        }
    }

    @Subscribe
    public void addPayPalEvent(SubmitPayPalEvent event) {
        if (mSetpays != null) {
            mSetpays.setPaypal_pay(1);
            setPaymentMethod = false;
        }
    }

    @Subscribe
    public void addAliPayEvent(SubmitAlipayEvent event) {
        if (mSetpays != null) {
            mSetpays.setAli_pay(1);
            setPaymentMethod = false;
        }
    }

    @Subscribe
    public void addWeChatPay(SubmitWeChatPayEvent event) {
        if (mSetpays != null) {
            mSetpays.setWechat_pay(1);
            setPaymentMethod = false;
        }
    }

    @Subscribe
    public void submitRealNameAuthenticationEvent(SubmitRealNameAuthenticationEvent event) {
        if (event.state == C.API_AUTHENTICATION_SUCCESS) {
            authenticationState = C.API_AUTHENTICATION_SUCCESS;
        } else {
            authenticationState = C.API_IN_AUTHENTICATION;
            initAuthentication();
        }
    }
}
